package net.kosev.battleships.model.ai;

import java.util.LinkedList;

import net.kosev.battleships.model.Board;
import net.kosev.battleships.model.Field;

/**
 * Normal Computer AI
 * 
 * @author Nikola
 *
 */
public class NormalEnemyAi extends EasyEnemyAI {
	
	/**
	 * Queue for upcoming moves
	 */
	private LinkedList<Integer> queue = new LinkedList<Integer>();
	
	/* (non-Javadoc)
	 * @see net.kosev.battleships.model.ai.EnemyAI#getFirePosition()
	 */
	public int getFirePosition() {
		final int index = getNext();
		final int[][] fields = board.getFields();
		
		final int i = index / Board.SIZE;
		final int j = index % Board.SIZE;
		
		if (fields[i][j] == Field.SHIP) {
			if (orientation == 0 || orientation == 1) {
				queue.offer((i - 1) * Board.SIZE + j);
				queue.offer(1);
				queue.offer((i + 1) * Board.SIZE + j);
				queue.offer(1);
			}
			if (orientation == 0 || orientation == 2) {
				queue.offer(i * Board.SIZE + (j - 1));
				queue.offer(2);
				queue.offer(i * Board.SIZE + (j + 1));
				queue.offer(2);
			}
		}
		
		return index;
	}
	
	/**
	 * Orientation helper
	 */
	private int orientation = 0; // 0 - none, 1 - vertical, 2 - horizontal
	
	/**
	 * Generate next fire position
	 * 
	 * @return	Next fire position
	 */
	private int getNext() {
		while (queue.size() != 0) {
			final int index = queue.poll();
			final int ori = queue.poll();
			if (orientation != 0 && orientation != ori) {
				continue;
			}
			final int[][] fields = board.getFields();
			
			final int i = index / Board.SIZE;
			final int j = index % Board.SIZE;
			
			if (i < 0 || i >= Board.SIZE || j < 0 || j >= Board.SIZE) {
				continue;
			}
			
			if (fields[i][j] == Field.WATER || fields[i][j] == Field.SHIP) {
				if (fields[i][j] == Field.SHIP) {
					orientation = ori;
				}
				return index;
			}
		}
		orientation = 0;
		
		return super.getFirePosition();
	}

}
